import Vue from "vue";
import Component from "vue-class-component";
import { Observer } from "mobx-vue";
import { commonOssGet} from 'src/utils/axios'
import "./upload.scss";

import ImageClipper from "../imageClipper/imageClipper.vue";

@Observer
@Component({
    props: {
        id: [String, Number], //用户id
        value: {
            type: [String, Array],
            default: ""
        },
        multiple: {
            type: String,
            default: null
        },
        isCompress: {
            //图片压缩的状态
            type: Boolean,
            default: true
        },
        isCut:{ //是否裁切
            type:Boolean,
            default:true
        },
        title: {
            type: String,
            default: ""
        },
        scale: {
            type: String,
            default: "1:1"
        },
        maxScale: {
            type: String,
            default: null
        },
        isHead: {
            type: Boolean,
            default: false
        },
        width: {
            type: Number,
            default: null
        },
        height: {
            type: Number,
            default: null
        },
        bucket:{
            type: String,
            default: 'upload' 
        },
        path:{
            type: String,
            default: '' 
        }
    },
    components: {
        ImageClipper
    }
})
export default class CsjUpload extends Vue {
    data() {
        return {
            imgUrl: "",
            imgUrl1:"",
            isImageClipper: false,
            fileImg: "", //原图
            clipperImgUrl: "" //原图的base64
        };
    }
    mounted() {
        let vm: any = this;
        setTimeout(() => {
            let ccuiFile: any = vm.$refs.ccuiFile;
            if (vm.multiple == "multiple") {
                vm.imgUrl = [];
                ccuiFile.setAttribute("multiple", "multiple");
            }
        }, 10);
    }
    //调用input的文件上传功能
    fileclick() {
        console.log("调用input的文件上传功能");
        let vm:any = this;
        let ccuiFile: any = vm.$refs.ccuiFile;
        if (!vm.isImageClipper) {
            ccuiFile.value = ''; // 清除input 选中的临时文件导致同文件无法显示问题
            ccuiFile.click();
        }
    }
    //文件上传
    uploadfile() {
        let vm:any = this;
        if (vm.multiple == "multiple") {
            vm.multiUploadFile();
        } else {
            vm.singleUploadFile();
        }
    }
    //多个上传
    multiUploadFile() {
        let vm: any = this;
        const file = vm.$refs.ccuiFile.files;
        //判断上传文件的类型是不是图片
        for (let i = 0; i < file.length; i++) {
            if (
                file[i].type != "image/jpg" &&
                file[i].type != "image/png" &&
                file[i].type != "image/bmp" &&
                file[i].type != "image/gif" &&
                file[i].type != "image/webp" &&
                file[i].type != "image/tiff" &&
                file[i].type != "image/jpeg" 
            ) {
                vm.$Message.error("上传失败，文件类型错误！");
                return;
            }
        }
        //批次上传到oss
        for (let j = 0; j < file.length; j++) {
            vm.ossGetWrap(file[j]);
        }
        vm.$emit("input", vm.imgUrl);
        vm.delivery();
    }
    async ossGetWrap(file) {
        let vm: any = this;
        let fileName = file.name.split(".")[0];
        let fd = new FormData();
        console.log('8888888888888',file);
        if( file.type == "video/quicktime"|| 
            file.type == "video/mp4" ||
            file.type == "video/MPEG-4" ||
            file.type == "video/avi" ||
            file.type == "video/mov" ||
            file.type == "video/rmvb" || 
            file.type == "video/3gp" || 
            file.type == "video/wvm")
        {
            await vm.ossGet(fd, fileName, file);
        }else{
            if (vm.isCompress && file.size / 1024 > 1025) {
                //若是需要压缩，大于1M，进行压缩上传
                await vm.photoCompress(
                    file,
                    {
                        quality: 0.2
                    },
                    function (base64Codes) {
                        var newfile = vm.blobToFile(vm.dataURLtoBlob(base64Codes), fileName);
                        vm.ossGet(fd, fileName, newfile);
                    }
                );
            } else {
                //小于等于1M 原图上传
                await vm.ossGet(fd, fileName, file);
            }
        }
            
    }
    //单个上传
    singleUploadFile() {
        let vm: any = this;
        let ccuiFile: any = vm.$refs.ccuiFile;
        const file = vm.$refs.ccuiFile.files[0];
        //jpg、png、bmp、gif、webp、tiff
        if (
            file.type != "image/jpg" &&
            file.type != "image/png" &&
            file.type != "image/bmp" &&
            file.type != "image/gif" &&
            file.type != "image/webp" &&
            file.type != "image/tiff" &&
            file.type != "image/jpeg" &&
            file.type != "video/quicktime" &&
            file.type != "video/mp4" &&
            file.type != "video/MPEG-4" &&
            file.type != "video/avi" &&
            file.type != "video/mov" &&
            file.type != "video/rmvb" &&
            file.type != "video/3gp" &&
            file.type != "video/wvm"
        ) {
            vm.$Message.error("上传失败，文件类型错误！");
            return;
        }
        vm.fileImg = file;
        if(vm.isCut){ //裁切
            let reader:any = new FileReader();
            reader.readAsDataURL(file); // 读出 base64
            reader.onload = (e)=>{
                vm.clipperImgUrl = (<any>e.target).result;
                ccuiFile.value = '';//防止再次打开同一张图片打不开的问题
                vm.isImageClipper = true;
            }
        }else{
            vm.ossGetWrap(vm.fileImg);
        }
    }
    //确认裁切
    confirm(data) {
        let vm: any = this;
        let xwindow: any = window;
        let file: any = "";
        vm.isImageClipper = false;
        //将data给oss
        let fileName = vm.fileImg.name.split(".")[0];
        const fd = new FormData();
        file = vm.blobToFile(vm.dataURLtoBlob(data), fileName); //将base64转化为二进制，再将二进制转化为文件，因为直接将base64转化为文件时的new file()在ie下有兼容
        if (vm.isCompress && file.size / 1024 > 1025) {
            //若是需要压缩，大于1M，进行压缩上传
            vm.photoCompress(
                file,
                {
                    quality: 0.2
                },
                function (base64Codes) {
                    var newfile = vm.blobToFile(vm.dataURLtoBlob(base64Codes), fileName);
                    vm.ossGet(fd, fileName, newfile);
                }
            );
        } else {
            //小于等于1M 原图上传
            vm.ossGet(fd, fileName, file);
        }
    }
    //取消裁切
    cancel() {
        let vm: any = this;
        vm.isImageClipper = false;
    }
    //将二进制转换成file
    blobToFile(theBlob, fileName) {
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
    }
    //将base64转化为二进制
    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(","),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }
    dataURLtoFile(dataurl, filename) {
        //将base64转换为文件
        var arr = dataurl.split(","),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        let out: any = new File([u8arr], filename, { type: mime });
        return out;
    }
    photoCompress(file, w, objDiv) {
        var ready = new FileReader();
        var vm = this;
        /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
        ready.readAsDataURL(file);
        ready.onload = function () {
            var re = this.result;
            vm.canvasDataURL(re, w, objDiv);
        };
    }
    canvasDataURL(path, obj, callback) {
        var img = new Image();
        img.src = path;
        img.onload = function () {
            var that: any = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            w = obj.width || w;
            h = obj.height || w / scale;
            var quality = 0.7; // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            var base64 = canvas.toDataURL("image/jpeg", quality);
            // 回调函数返回base64的值
            callback(base64);
        };
    }
    //oss上传
    async ossGet(fd, fileName, file) {
        let vm: any = this;
        let params:any = {
            dir:vm.bucket
        }
        console.log('00000000',file);
        let out:any = await commonOssGet(params);
        if (!out.status) {
            const signature = out.data.signature
            const policy = out.data.policy
            const host = out.data.host
            const dns_host = out.data.dns_host
            const accessid = out.data.accessid
            const saveName = new Date().getTime() + 300000
            const startsWith = "upload/"
            fd.append("OSSAccessKeyId", accessid);
            fd.append("policy", policy);
            fd.append("signature", signature);
            fd.append("key",  startsWith + saveName);
            fd.append("success_action_status", 200);
            fd.append("file", file, saveName);
            const xhr = new XMLHttpRequest();
            xhr.open("post", host, true);
            xhr.addEventListener("load",e => {
                    let target: any = e.target;
                    if (target.status !== 200) {
                        console.log(target.response);
                        console.log("上传失败！");
                        return;
                    }
                    if (target.status === 200) {
                        let imageUrl: any = startsWith + saveName
                        let imageUrl1: any = startsWith + saveName 
                        if (vm.multiple == "multiple") {
                            vm.imgUrl.push(imageUrl);
                        } else {
                            vm.imgUrl = imageUrl;
                            vm.imgUrl1 = imageUrl1;
                            vm.$emit("input", vm.imgUrl);
                            console.log('9999999999999',vm.imgUrl);
                            vm.delivery();
                        }
                    }
                },
                false
            );
            xhr.send(fd);
        } else {
            vm.$Message.error(out.errorMsg);
        }
    }
    //上传的图片返回给后端
    delivery() {
        let vm: any = this;
        this.$emit("handleUpload", vm.imgUrl1);
    }
}
